from django import template
from django import forms
from django.http import HttpResponseRedirect
from genericview.views import HttpRedirectException
from pirateissues.models import Topic, Issue
from django.shortcuts import get_object_or_404

register = template.Library()

@register.tag("pirate-get-new-issue-list")
def do_new_issue_list(parser, token):
	nodelist = parser.parse(('end-get-new-issue-list',))
	parser.delete_first_token()
	return GetNewIssueListNode(nodelist)

@register.tag("pirate-get-issue")
def do_new_issue_list(parser, token):
	nodelist = parser.parse(('end-get-issue',))
	parser.delete_first_token()
	return GetIssueNode(nodelist)

#This method returns the newest issues
class GetNewIssueListNode(template.Node):
	def __init__(self, nodelist):
		self._nodelist = nodelist

	def render(self, context):

		if 'request' not in context or 'path' not in context or 'topic' not in context:
			raise ValueError("This tag requires four specific argments to be supplied: " +
								 "'request' of type HTTPRequest, 'path' of type string, 'topic' of type int and 'page_num' of type int")
		

		request = context['request']
		path	= context['path']
		topic = context['topic']
		try: page_num = context['page_num']
		except: page_num = 0

		if 'pirate_issues' in context:
			pirate_issues = context['pirate_issues'].copy()
		else:
			pirate_issues = {}
		#get the page page_num of issues for topic_id, ordered by date. 20 per page.
		issue_list = Issue.objects.filter(topic__id=topic.id)
		issue_list = issue_list.order_by('-pub_date')
		issue_list = issue_list[page_num*20:page_num*20+20]			
		pirate_issues["issue_list"] = issue_list[page_num*20:page_num*20+20]
		

		context.push()
		context['pirate_issues'] = pirate_issues
		output = self._nodelist.render(context)
		context.pop()

		return output

class GetIssueNode(template.Node):
	def __init__(self, nodelist):
		self._nodelist = nodelist

	def render(self, context):

		if 'request' not in context or 'path' not in context or 'args' not in context:
			raise ValueError("This tag requires four specific argments to be supplied: " +
								 "'request' of type HTTPRequest, 'path' of type string, 'topic' of type int and 'page_num' of type int")
		

		request = context['request']
		path	= context['path']
		issue_id = context['args'][0] #first argument should be issue id


		if 'pirate_issue' in context:
			pirate_issue = context['pirate_issue'].copy()
		else:
			pirate_issue = {}

		issue = get_object_or_404(Issue,pk=issue_id)
		pirate_issue['issue'] = issue
		context.push()
		context['pirate_issue'] = pirate_issue
		output = self._nodelist.render(context)
		context.pop()

		return output


